require 'bundler'
require 'rubygems/package'

task :default => :gen

BUILD_DIR          = "build"
MARKDOWN_FILES     = Rake::FileList.new("source/_tmp/*.md")
TOPIC_MAP          = "#{BUILD_DIR}/_topic_map.yml"
ADOC_VARIABLES     = FileList.new('source/variables.adoc',
 'source/contributing/variables.adoc',
 'source/getting-started/variables.adoc',
 'source/openshift/variables.adoc',
 'source/troubleshooting/variables.adoc',
 'source/using/variables.adoc'
)
GENERATED_ADOC_DIR = "source/command-ref"
ADOC_FILES = Rake::FileList.new do |list|
  MARKDOWN_FILES.each do |f|
    adoc = f.ext(".adoc")
    adoc = File.split(adoc)[1]
    adoc = File.join(GENERATED_ADOC_DIR, adoc)
    list.add(adoc)
  end
end

task :init do
  mkdir_p BUILD_DIR
end

task :clean do
  rm_f Rake::FileList.new("#{GENERATED_ADOC_DIR}/*.adoc")
  rm_rf BUILD_DIR
  rm_f ADOC_VARIABLES
  # find ditaa images based on the fact that they have a cache file
  DITAA_IMAGES = Rake::FileList.new do |list|
    Rake::FileList.new("source/**/images/*-template.png.cache").each do |f|
      list.add(f)
      list.add(f.gsub(/\.cache/, ''))
    end
  end
  rm_f DITAA_IMAGES
end

file TOPIC_MAP => [:init, 'source/_topic_map.yml'] do
  if Dir.glob("#{GENERATED_ADOC_DIR}/*.adoc").empty? then
    cp 'source/_topic_map.yml', TOPIC_MAP
  end
end

desc 'Convert the generated command synopsis files from Markdown to Asciidoc'
task :markdown_to_asciidoc => [TOPIC_MAP, :asciidoc]
task :asciidoc => ADOC_FILES
rule ".adoc" => ->(f){source_for_adoc(f)} do |t|
  # convert markdown to asciidoc
  base_name = File.basename(t.name, ".adoc")
  adoc_file = File.join(GENERATED_ADOC_DIR, "#{base_name}.adoc" )
  sh "pandoc --atx-headers --to=asciidoc --output=#{adoc_file} #{t.source}"

  # adjust links in generated asciidoc
  adoc_content = File.read(adoc_file)
  adoc_new = adoc_content.gsub(/\.md\[/, "{outfilesuffix}[")
  # adjust header levels
  adoc_new = adoc_new.gsub(/^=/, "")
  File.open(adoc_file, "w") {|file| file.puts adoc_new }

  # update topic map
  File.open(TOPIC_MAP, "ab:UTF-8") do |file|
    file.puts "      - Name: #{base_name.gsub('_',' ')}"
    file.puts "        File: #{base_name}"
  end
end

desc 'Generate site'
task :gen => [:init, :markdown_to_asciidoc, :adoc_variables] do
  sh "bundle exec middleman build --no-clean"
end

desc 'Serve site'
task :serve, [:server_args] => [:init, :markdown_to_asciidoc, :adoc_variables] do |t, args|
  if args[:server_args].nil? then
    sh "bundle exec middleman server"
  else
    sh "cp -f source/using/images/minishift-architecture-template.png source/using/images/minishift-architecture.png"
    sh "bundle exec middleman server #{args[:server_args]}"
  end
end

desc 'Create adoc tar bundle'
task :adoc_tar => [:init, :adoc_variables, :markdown_to_asciidoc] do
  file_list = FileList.new('source/**/*.adoc', 'source/**/images/*', TOPIC_MAP, ADOC_VARIABLES)
  file_list.exclude("source/images/**")
  File.open("#{BUILD_DIR}/minishift-adoc.tar", "wb") do |file|
    Gem::Package::TarWriter.new(file) do |tar|
      file_list.each { |f|
        tar.add_file(f, 0444) { |io|
          if File.extname(f) == ".adoc" then
            adoc_content = File.read(f)
            adoc_content = adoc_content.gsub(/include::.*variables\.adoc\[\]/, "include::minishift/variables.adoc[]")
            io.write(adoc_content)
          else
            io.write(File.read(f))
          end
        }
      }
    end
  end
end

desc 'Create adoc variables'
task :adoc_variables => :init do
  minishift_version    = ENV['MINISHIFT_VERSION']    || 'unset'
  openshift_version    = ENV['OPENSHIFT_VERSION']    || 'unset'
  centos_iso_version   = ENV['CENTOS_ISO_VERSION']   || 'unset'

  contents = <<EOF
:project: Minishift
:download-url: https://github.com/minishift/minishift/releases
:download-text: {project} Releases

:minishift-version: #{minishift_version}
:openshift-version: #{openshift_version}
:centos-iso-version: #{centos_iso_version}
EOF

  ADOC_VARIABLES.each { |f| File.write(f, contents) }
end

desc 'Check links'
task :link_check => :gen do
  # Limiting us here to check for 4xx errors which will cover broken links
  # Without this restriction we are getting errors for TLS certificate verification of
  # docs.okd.io. This can be prevented by custom installing missing certificates, but
  # for now that is not required (HF)

  # Don't need minishift-architecture.html file as it is unnecessary
  # TODO: Investigate asciidoctor-diagram gem to see how we can prevent it
  sh "rm -f build/using/minishift-architecture.html"
  sh "cp -f build/using/images/minishift-architecture-template.png build/using/images/minishift-architecture.png"
  sh "bundle exec htmlproofer build --only-4xx"
end

def source_for_adoc(adoc_file)
  MARKDOWN_FILES.detect do |f|
    markdown_source = f.ext('')
    markdown_source = File.split(markdown_source)[1]

    adoc_target = adoc_file.ext('')
    adoc_target = File.split(adoc_target)[1]

    markdown_source == adoc_target
  end
end

def createAdocTargetFiles
  MARKDOWN_FILES.each do |f|
    p "#{f}"
  end
end
